package com.yonyou.gmmc.service.points.eventhandle;

import org.marketing.common.dto.EventDataDTO;
import org.marketing.common.event.BizEvent;
import org.marketing.common.event.EventPointActivityDTO;
import org.marketing.common.event.enums.EventConstant;
import org.marketing.common.event.enums.EventConstant.EventBizStep;
import org.marketing.common.event.enums.EventConstant.EventBizType;
import org.marketing.common.util.MapConverUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yonyou.gmmc.service.points.exception.PointsException;
import com.yonyou.gmmc.service.points.model.TmPointsRule;
import com.yonyou.gmmc.service.points.service.PointsPayService;
import com.yonyou.gmmc.service.points.service.PointsRuleService;
import com.yonyou.gmmc.service.points.util.SpringUtil;

/**
 * 积分活动加积分事件处理
 * 
 * @author liyujiao
 *
 */
public class PointActivityEventHandler extends AbstractEventHandle {

	private static Logger logger = LoggerFactory.getLogger(PointActivityEventHandler.class);

	private static EventBizType BizType = EventConstant.EventBizType.POINT_ACTIVITY;

	private static EventBizStep BizStep = EventConstant.EventBizStep.POINT_ACTIVITY_GET_POINT;

	@Override
	protected String getHandleInfo() {
		return "积分活动,积分事件处理";
	}

	
	/**
	 * 主要进行数据转换
	 */
	@Override
	protected EventPointActivityDTO preTransform(BizEvent event) {
		EventPointActivityDTO o = new EventPointActivityDTO();
		try {
			o = (EventPointActivityDTO) MapConverUtil.map2POStrict(event.getEventData(), o);
			logger.info(o.toString());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			this.backInfo = "eventData中的业务数据不能识别：" + e.getMessage();
			throw new PointsException(PointsException.EVENT_CONVERT_FAILD,"eventData中的业务数据不能识别");
		}
		return o;
	}

	/**
	 * 积分处理的逻辑
	 */
	@Override
	protected boolean pay(EventDataDTO eventData) throws PointsException {

		// 获取到业务数据
		EventPointActivityDTO thisEventData = (EventPointActivityDTO) eventData;

		PointsRuleService pointsRuleService = (PointsRuleService) SpringUtil.getBean("pointsRuleService");

		// 获取到规则
		TmPointsRule rule = pointsRuleService.getRuleByBIZ(BizType.getCodeLong(), BizStep.getCodeLong());

		if (rule != null) {
			//Long points = rule.getPointsNum();
			PointsPayService pointsPayService = (PointsPayService) SpringUtil.getBean("pointsPayService");
			pointsPayService.payPointsToUser(thisEventData.getChangeNum(), thisEventData.getUserId(), null,rule.getRemark(),String.valueOf(thisEventData.getUserId()), BizStep.getCode());
		} else {
			this.backInfo = "未找到对应的积分规则：";
			throw new PointsException(PointsException.RULE_NOTFOUND, "未找到对应的积分规则");
		}
		return false;
	}


}
